package dao

import (
	"fmt"
	"go-admin/global"
	"go-admin/internal/model"
	mr "go-admin/internal/model/api/model_request"
	_const "go-admin/internal/model/const"
	"time"
)

func (d *Dao) CreateDept(param *mr.CreateDeptRequest) (string, error) {
	dept := model.Dept{
		CommonModel: model.CommonModel{
			Id:    global.GetId(),
			IsDel: _const.ISDEL,
		},
		DeptName: param.DeptName,
		ParentId: param.ParentId,
		Remark:   param.Remark,
		IsBanned: _const.ISBANNED,
		Sort:     param.Sort,
	}
	// 获取当前父id的部门信息
	parentDept, err := dept.GetDeptById(d.Engine, dept.ParentId)
	if err != nil {
		return "", err
	}
	// 如果获取的id为0，说明没有找到当前行的数据,为顶级的数据
	if parentDept.Id == "" {
		dept.DeptPath = fmt.Sprintf("/0/%v", dept.Id)
	} else {
		dept.DeptPath = fmt.Sprintf("%v/%v", parentDept.DeptPath, dept.Id)
	}
	return dept.Create(d.Engine)
}

// 根据id获取详情
func (d *Dao) GetDeptById(id string) (*model.Dept, error) {
	dept := model.Dept{
		CommonModel: model.CommonModel{Id: id},
	}
	return dept.GetDeptById(d.Engine, id)
}

func (d *Dao) GetDeptListAll() ([]*model.Dept, error) {
	dept := model.Dept{}
	return dept.ListAll(d.Engine)
}

func (d *Dao) UpdateDept(param *mr.UpdateDeptRequest) error {
	dept := model.Dept{
		CommonModel: model.CommonModel{
			Id: param.Id,
		},
	}
	values := map[string]interface{}{
		"is_banned":   param.IsBanned,
		"modified_on": time.Now().Local().Unix(),
		"dept_name":   param.DeptName,
		"sort":        param.Sort,
	}
	if param.Remark != "" {
		values["remark"] = param.Remark
	}
	return dept.Update(d.Engine, values)
}

// 删除
func (d *Dao) DeleteDept(id string) error {
	dept := model.Dept{
		CommonModel: model.CommonModel{
			Id: id,
		},
	}
	values := map[string]interface{}{
		"deleted_on": time.Now().Local().Unix(),
		"is_del":     _const.DEL,
	}
	return dept.Delete(d.Engine, values)
}

func (d *Dao) GetDeptByDeptName(deptName string) (*model.Dept, error) {
	dept := model.Dept{}
	return dept.GetDeptByDeptName(d.Engine, deptName)
}
